package com.spider.task;

import com.spider.entites.Task;
import com.spider.mapper.ConfMapper;
import com.spider.mapper.TaskMapper;
import com.spider.runnable.DetailPageRunnable;
import com.spider.websocket.WebSocketServer;
import org.apache.commons.dbutils.QueryRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author panglin
 * @date 2020/11/21 14:21
 */
@Component
public class TimerTask {

    private static final ThreadPoolExecutor POOL = new ThreadPoolExecutor(2, 4, 3, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10), (r) -> {
        Thread thread = new Thread(r);
        thread.setName("--detailTask--pool--" + thread.getId());
        thread.setUncaughtExceptionHandler((t, e) -> e.printStackTrace());
        return thread;
    });

    private static final Logger LOGGER = LoggerFactory.getLogger(TimerTask.class);

    @Resource
    private TaskMapper taskMapper;

    @Resource
    private ConfMapper confMapper;

    @Resource
    private QueryRunner queryRunner;

    @Resource
    private DetailPageRunnable runnable;

    @Scheduled(cron = "0/15 * * * * ?")
    public void timerTask() {
        List<Task> tasks = this.taskMapper.queryTasksInTimer();
        tasks.forEach(t -> {
            if (t.getRunStatus() == 1 && t.getSalveStatus() == 0) {
                this.taskMapper.updateSalveStatus(t.getId());
                POOL.execute(this.runnable.initTask(t, this.queryRunner, this.confMapper.querySetByTid(t.getId())));
                LOGGER.info("详情页任务开始,任务名称:{}", t.getTaskName());
            }
        });
        WebSocketServer.sendMessageByGroup("开始更新列表");
    }
}
